﻿
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_CertifiedHousehold_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            Bind2Grid()
            BindToGrid()
            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
        End If
    End Sub
    Private Sub Bind2Grid()
        Using Data As New VSEntities
          

            Dim pro = (From q In Data.Provinces Where q.ParentId = 171 Order By q.Title Select q).ToList
            With ddlProvince
                .DataTextField = "Title"
                .DataValueField = "Id"
                .DataSource = pro
                .DataBind()
                .Items.Insert(0, New ListItem("--- Tất cả ---", "-1"))
            End With
        End Using
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1 _
            , Optional ByVal strCertifiedCode As String = "" _
              , Optional ByVal dtmCertifiedDateFrom As Date = #1/1/1900# _
              , Optional ByVal dtmCertifiedDateTo As Date = #12/31/3999# _
              , Optional ByVal strBiz_VietName As String = "" _
              , Optional ByVal strOw_Name As String = "" _
              , Optional ByVal intOw_Sex As Integer = -1 _
              , Optional ByVal strOw_BirthDate As String = "" _
              , Optional ByVal strOw_Nationality_ID As String = "" _
              , Optional ByVal strOw_CardID As String = "" _
              , Optional ByVal dtmOw_CardDateFrom As Date = #1/1/1900# _
              , Optional ByVal dtmOw_CardDateTo As Date = #12/31/3999# _
              , Optional ByVal strOw_Provider_ID As String = "" _
              , Optional ByVal strOw_Tel As String = "" _
              , Optional ByVal strOw_Email As String = "" _
              , Optional ByVal strOw_WebSite As String = "" _
              , Optional ByVal strOw_Resident As String = "" _
              , Optional ByVal strOw_Present As String = "" _
              , Optional ByVal strCertifiedDeptName As String = "" _
              , Optional ByVal strCertifiedSignerName As String = "" _
              , Optional ByVal strCertifiedStatus As String = "" _
              , Optional ByVal intCertifiedIndex As Integer = -1 _
              , Optional ByVal strOw_TaxCode As String = "" _
              , Optional ByVal intProvinceId As Integer = -1 _
      )
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, strCertifiedCode.ToString, dtmCertifiedDateFrom, dtmCertifiedDateTo, strBiz_VietName.ToString, strOw_Name.ToString, intOw_Sex.ToString, strOw_BirthDate.ToString, strOw_Nationality_ID.ToString, strOw_CardID.ToString, dtmOw_CardDateFrom.ToString, dtmOw_CardDateTo.ToString, strOw_Provider_ID.ToString, strOw_Tel.ToString, strOw_Email.ToString, strOw_WebSite.ToString, strOw_Resident.ToString, strOw_Present.ToString, strCertifiedDeptName.ToString, strCertifiedSignerName.ToString, strCertifiedStatus.ToString, intCertifiedIndex.ToString, strOw_TaxCode.ToString, intProvinceId.ToString}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            intProvinceId = ddlProvince.SelectedValue
            Dim p As List(Of uspCertifiedHouseholdSelectAll_Result) = data.uspCertifiedHouseholdSelectAll(strCertifiedCode _
                    , dtmCertifiedDateFrom _
                    , dtmCertifiedDateTo _
                    , strBiz_VietName _
                    , strOw_Name _
                    , intOw_Sex _
                    , strOw_Nationality_ID _
                    , strOw_CardID _
                    , dtmOw_CardDateFrom _
                    , dtmOw_CardDateTo _
                    , strOw_Provider_ID _
                    , strOw_Tel _
                    , strOw_Email _
                    , strOw_WebSite _
                    , strOw_Resident _
                    , strOw_Present _
                    , strCertifiedDeptName _
                    , strCertifiedSignerName _
                    , strCertifiedStatus _
                    , strOw_TaxCode _
                    , 1 _
                    , intProvinceId _
                    , iPage _
                    , intPag_Size).ToList
            Dim strKey_Name() As String = {"CertifiedID", "CertifiedCode", "Ow_Sex", "ProvinceId"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip) _
       , arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
       , arrSearch(6) _
       , arrSearch(7) _
       , arrSearch(8) _
       , arrSearch(9) _
       , arrSearch(10) _
       , arrSearch(11) _
       , arrSearch(12) _
       , arrSearch(13) _
       , arrSearch(14) _
       , arrSearch(15) _
       , arrSearch(16) _
       , arrSearch(17) _
       , arrSearch(18) _
       , arrSearch(19) _
       , arrSearch(20) _
       , arrSearch(21) _
       , arrSearch(22) _
       , arrSearch(23) _
            )
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("CertifiedID").ToString
            Dim q = (From p In data.CertifiedHouseholds Where p.CertifiedID = intId Select p).FirstOrDefault
            Try
                data.CertifiedHouseholds.DeleteObject(q)
                data.SaveChanges()
                Insert_App_Log("Insert  CertifiedHousehold:" & q.CertifiedCode & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("CertifiedID").ToString
                        Dim q = (From p In data.CertifiedHouseholds Where p.CertifiedID = intId Select p).FirstOrDefault
                        Try
                            data.CertifiedHouseholds.DeleteObject(q)
                            Insert_App_Log("Insert  Giấy CN ĐKKD:" & q.CertifiedCode & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            data.SaveChanges()
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = "../../Page/QuanlyHoSo/Edit.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
            Dim hplCertifiedcode As HyperLink = CType(e.Row.FindControl("hplCertifiedcode"), HyperLink)
            hplCertifiedcode.NavigateUrl = "../../Page/CertifiedHousehold/Detail.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
            If Not grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode") Is Nothing Then
                hplCertifiedcode.Text = grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode").ToString

            End If
            Dim lblGioTinh As Label = CType(e.Row.FindControl("lblGioTinh"), Label)
            lblGioTinh.Text = IIf(grdShow.DataKeys(e.Row.RowIndex)("Ow_Sex") = 1, "Nam", "Nữ")
            Dim lblHuyen As Label = CType(e.Row.FindControl("lblHuyen"), Label)
            Using _data As New VSEntities
                Dim _ProvinceId As Integer = grdShow.DataKeys(e.Row.RowIndex)("ProvinceId")
                Dim p = (From q In _data.Provinces Where q.Id = _ProvinceId Select q).FirstOrDefault
                If Not p Is Nothing Then
                    lblHuyen.Text = p.Title
                End If
            End Using


        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Dim certFrom As DateTime = IIf(txtCertifieddateFrom.Text.Trim <> "", StringToDate(txtCertifieddateFrom.Text.Trim), "1950/01/01")
        Dim certTo As DateTime = IIf(txtCertifieddateTo.Text.Trim <> "", StringToDate(txtCertifieddateTo.Text.Trim), "3999/12/31")
        Dim CardFrom As DateTime = IIf(txtOw_carddateFrom.Text.Trim <> "", StringToDate(txtOw_carddateFrom.Text.Trim), "1950/01/01")
        Dim CardTo As DateTime = IIf(txtOw_carddateTo.Text.Trim <> "", StringToDate(txtOw_carddateTo.Text.Trim), "3999/12/31")

        BindToGrid(1 _
             , txtCertifiedcode.Text.Trim _
            , certFrom _
            , certTo _
            , txtBiz_vietname.Text.Trim _
            , txtOw_name.Text.Trim _
            , CInt(IIf(String.IsNullOrEmpty(txtOw_sex.Text) = True, -1, txtOw_sex.Text)) _
            , txtOw_birthdate.Text.Trim _
            , txtOw_nationality_id.Text.Trim _
            , txtOw_cardid.Text.Trim _
           , CardFrom _
            , CardTo _
            , txtOw_provider_id.Text.Trim _
            , txtOw_tel.Text.Trim _
            , txtOw_fax.Text.Trim _
            , txtOw_email.Text.Trim _
            , txtOw_resident.Text.Trim _
            , txtCertifiedsignername.Text.Trim _
            , txtCertifieddeptname.Text.Trim _
            )
        'BindToGrid(1 _
        '     , txtCertifiedcode.Text.Trim _
        '    , certFrom _
        '    , certTo _
        '    , txtBiz_vietname.Text.Trim _
        '    , txtOw_name.Text.Trim _
        '    , CInt(IIf(String.IsNullOrEmpty(txtOw_sex.Text) = True, -1, txtOw_sex.Text)) _
        '    , txtOw_birthdate.Text.Trim _
        '    , txtOw_nationality_id.Text.Trim _
        '    , txtOw_cardid.Text.Trim _
        '   , CardFrom _
        '    , CardTo _
        ', txtOw_provider_id.Text.Trim _
        ', txtOw_tel.Text.Trim _
        ', txtOw_fax.Text.Trim _
        ', txtOw_email.Text.Trim _
        ', txtOw_resident.Text.Trim _
        ', txtOw_present.Text.Trim _
        ', txtCertifieddeptname.Text.Trim _
        ', txtCertifiedsignername.Text.Trim _
        ', txtCertifiedstatus.Text.Trim _
        ', txtOw_taxcode.Text.Trim _
        ', CInt(IIf(String.IsNullOrEmpty(txtProvinceid.Text) = True, -1, txtProvinceid.Text)) _
        ')

    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
       , arrSearch(6) _
       , arrSearch(7) _
       , arrSearch(8) _
       , arrSearch(9) _
       , arrSearch(10) _
       , arrSearch(11) _
       , arrSearch(12) _
       , arrSearch(13) _
       , arrSearch(14) _
       , arrSearch(15) _
       , arrSearch(16) _
       , arrSearch(17) _
       , arrSearch(18) _
       , arrSearch(19) _
       , arrSearch(20) _
       , arrSearch(21) _
       , arrSearch(22) _
       , arrSearch(23) _
         )
    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click

        txtCertifiedcode.Text = ""
        txtCertifieddateFrom.Text = ""
        txtCertifieddateTo.Text = ""

        txtBiz_vietname.Text = ""

        txtOw_name.Text = ""
        txtOw_sex.Text = ""
        txtOw_birthdate.Text = ""
        'txtOw_national_id.Text = ""
        txtOw_nationality_id.Text = ""
        txtOw_cardid.Text = ""
        txtOw_carddateFrom.Text = ""
        txtOw_carddateTo.Text = ""
        txtOw_provider_id.Text = ""
     
        txtOw_docofficertifiedid.Text = ""
        txtOw_tel.Text = ""
        txtOw_fax.Text = ""
        txtOw_email.Text = ""

        txtOw_resident.Text = ""
        txtOw_present.Text = ""
    
        txtCertifieddeptname.Text = ""
     
        txtCertifiedsignername.Text = ""

        txtCertifiedstatus.Text = ""
        
        txtOw_taxcode.Text = ""
        ddlProvince.SelectedIndex = -1
        drpPage_Size.SelectedIndex = -1
        BindToGrid(1)
    End Sub
#End Region
End Class
